package chpt10;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class LoginDialog2 extends JDialog {
	private JTextField usernameField;
	private JPasswordField passwordField;

	// 构造函数
	public LoginDialog2(JFrame parent) {
		// 设置窗口标题
		super(parent, "登录对话框", true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		// 创建用户名和密码的标签和文本框
		JLabel usernameLabel = new JLabel("用户名:", SwingConstants.RIGHT);
		usernameField = new JTextField(10);
		JLabel passwordLabel = new JLabel("密码:", SwingConstants.RIGHT);
		passwordField = new JPasswordField(10);

		// 创建登录按钮
		JButton loginButton = new JButton("登录");
		loginButton.addActionListener(e -> {
			String username = usernameField.getText();
			char[] pwd = passwordField.getPassword();
			String password = new String(pwd);
			if (username.equals("admin") && password.equals("admin123")) {
				JOptionPane.showMessageDialog(null, "登录成功");
			} else {
				JOptionPane.showMessageDialog(null, "用户名或密码错误");
			}
			// 为了安全，使用完数组内容后应清除密码数组的内容
			Arrays.fill(pwd, '\0');
		});

		JButton cancelButton = new JButton("取消");
		cancelButton.addActionListener(e -> dispose());

		// 创建布局管理器并设置布局
		setLayout(new GridLayout(3, 2));

		// 将标签、文本框和按钮添加到窗口中
		add(usernameLabel);
		add(usernameField);
		add(passwordLabel);
		add(passwordField);
		add(loginButton);
		add(cancelButton);

		// 设置窗口大小和关闭操作
		pack();
		setLocationRelativeTo(null);

	}

	// 主方法
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				LoginDialog2 dialog = new LoginDialog2(null);
				dialog.setVisible(true);
			}
		});
	}
}
